﻿using System;
using System.ComponentModel.DataAnnotations;
using System.Text.RegularExpressions;

namespace Webbness.Mvc.Validators
{
    [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false)]
    public class EmailValidatorAttribute : ValidationAttribute
    {
        private const string _defaultErrorMessage = "'{0}' must be in aaa@bbb.ccc format.";

        public EmailValidatorAttribute() : base(_defaultErrorMessage)
        {
        }

        public EmailValidatorAttribute(bool strict) : this()
        {
            Strict = strict;
        }

        public bool Strict { get; set; }

        public override bool IsValid(object value)
        {
            if (value == null)
                return false;

            bool result;
            if (!Strict)
            {
                const string patternLenient = @"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*";
                var reLenient = new Regex(patternLenient);
                result = reLenient.IsMatch(value.ToString());
            }
            else
            {
                const string patternStrict = @"^(([^<>()[\]\\.,;:\s@\""]+"
                                             + @"(\.[^<>()[\]\\.,;:\s@\""]+)*)|(\"".+\""))@"
                                             + @"((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}"
                                             + @"\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+"
                                             + @"[a-zA-Z]{2,}))$";
                var reStrict = new Regex(patternStrict);
                result = reStrict.IsMatch(value.ToString());
            }
            return result;
        }
    }
}